/*
 * $Id: TestContentService.java 216 2008-03-24 00:49:31Z jasta $
 *
 * Copyright (C) 2008 Josh Guilfoyle <jasta@devtcg.org>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 */

package org.devtcg.five.music.activity;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.devtcg.five.music.R;
import org.devtcg.five.service.ContentState;
import org.devtcg.five.service.IContentObserver;
import org.devtcg.five.service.IContentService;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class TestContentService extends Activity
{
	private static final String TAG = "TestContentService";

	private Button mBtnDownload;
	private Button mBtnPlay;
	private Button mBtnStop;
	private ProgressBar mProgress;
	
	private MediaPlayer mPlayer;

	private long mContentId;
	private Uri mCacheUri;

	private IContentService mService;

	private Handler mHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			mProgress.setSecondaryProgress(msg.what);
			
			if (msg.what >= 10 && mBtnPlay.isEnabled() == false)
				mBtnPlay.setEnabled(true);
		}
	};

	@Override
	protected void onCreate(Bundle icicle)
	{
		super.onCreate(icicle);
		setContentView(R.layout.test_content_service);
		
    	Uri song = getIntent().getData();
    	
    	Cursor c = getContentResolver().query(song,
    	  new String[] { "_id", "content_id", "title" }, 
    	  null, null, null);
    	
    	if (c.count() == 0)
    	{
    		Toast.makeText(this, "Something went very wrong", Toast.LENGTH_SHORT).show();
    		finish();
    		return;
    	}

    	c.first();
    	
    	mContentId = c.getLong(1);

    	TextView songInfo = (TextView)findViewById(R.id.song_info);
    	songInfo.setText(c.getString(2));

    	bindContentService();

    	mBtnDownload = (Button)findViewById(R.id.download);
    	mBtnDownload.setOnClickListener(mDownload);

    	mBtnPlay = (Button)findViewById(R.id.play);
    	mBtnPlay.setOnClickListener(mPlay);
    	mBtnPlay.setEnabled(false);
    	
    	mBtnStop = (Button)findViewById(R.id.stop);
    	mBtnStop.setOnClickListener(mStop);
    	mBtnStop.setEnabled(false);
    	
    	mProgress = (ProgressBar)findViewById(R.id.download_progress);    	
	}

	@Override
	protected void onDestroy()
	{
//		if (mService != null)
//		{
//			/* This is harmless if the download is not active currently. */
//			try { mService.stopDownload(mContentId); }
//			catch (DeadObjectException e) { }
//		}

		unbindService(mConnection);
		super.onDestroy();
	}

	private void bindContentService()
	{
    	ComponentName contentService = new ComponentName("org.devtcg.five",
    	  "org.devtcg.five.service.ContentService");

		bindService(new Intent().setComponent(contentService),
 		  mConnection, BIND_AUTO_CREATE);
	}

	private final ServiceConnection mConnection = new ServiceConnection()
	{
		public void onServiceConnected(ComponentName name, IBinder service)
		{
			mService = IContentService.Stub.asInterface(service);			
			Log.d(TAG, "Connected to content service!");
		}

		public void onServiceDisconnected(ComponentName name)
		{
			Toast.makeText(TestContentService.this, "Service disconnected?", Toast.LENGTH_SHORT).show();
			mService = null;

			mBtnDownload.setEnabled(false);
			mBtnPlay.setEnabled(false);
		}
	};

	private final OnClickListener mDownload = new OnClickListener()
	{
		public void onClick(View v)
		{
			if (mService == null)
			{
				Toast.makeText(TestContentService.this,
				  "Not connected to service?", Toast.LENGTH_LONG).show();
				return;
			}

			try {
				ContentState state = 
				  mService.getContent(mContentId, mContentObserver);
			} catch (DeadObjectException e) {
				mService = null;
				bindContentService();
			}
		}
	};

	private final IContentObserver.Stub mContentObserver = new IContentObserver.Stub()
	{
		public void error(long contentId, final String msg)
		{
			Log.d(TAG, "error(" + contentId + ", " + msg + ")");

			mHandler.post(new Runnable() {
				public void run()
				{
					Toast.makeText(TestContentService.this, "Error: " + msg, Toast.LENGTH_SHORT).show();					
				}
			});
		}

		public void finished(long contentId, Uri uri, ContentState state)
		{
			Log.d(TAG, "finished(" + contentId + ", " + uri + ", " + state + ")");
			mCacheUri = uri;

			mHandler.post(new Runnable() {
				public void run()
				{
					mBtnPlay.setEnabled(true);					
				}
			});
		}

		public long updateInterval()
		{
			return 1000;
		}

		public void updateProgress(long contentId, Uri uri, ContentState state)
		{
			mCacheUri = uri;

			if (state.total == -1 || state.ready > state.total)
				mProgress.setIndeterminate(true);
			else
			{
				float pct = ((float)state.ready / (float)state.total);
				final int progress = (int)(pct * 100.0);

				mHandler.sendMessage(mHandler.obtainMessage(progress));
			}
		}
	};

	private final OnClickListener mPlay = new OnClickListener()
	{
		public void onClick(View v)
		{
			mPlayer = new MediaPlayer();
			
			Cursor c = getContentResolver().query(mCacheUri,
			  new String[] { "_data" }, null, null, null);
			
			if (c.count() == 0)
			{
				Toast.makeText(TestContentService.this,
				  "What the hell?", Toast.LENGTH_LONG).show();
				return;
			}
			
			c.first();
			String path = c.getString(0);

			try
			{
				mPlayer.setDataSource(path);
				mPlayer.prepare();
			}
			catch (Exception e)
			{
				Toast.makeText(TestContentService.this,
				  "Eek! " + e.toString(), Toast.LENGTH_LONG).show();
				Log.d(TAG, "Eek!", e);
				mPlayer = null;
				return;
			}

			mPlayer.start();
			mBtnStop.setEnabled(true);
			mBtnPlay.setEnabled(false);
		}
	};

	private final OnClickListener mStop = new OnClickListener()
	{
		public void onClick(View v)
		{
			if (mPlayer == null)
			{
				Toast.makeText(TestContentService.this,
				  "Uhm, not playing", Toast.LENGTH_LONG).show();
				return;
			}

			mPlayer.stop();
			mBtnStop.setEnabled(false);
			mBtnPlay.setEnabled(true);
		}
	};
}
